<template>
  <div v-loading="loading">
    <div class="pub-detail-title-btn">
      <template v-if="state !== 3">
        <a-button
          type="primary"
          @click="openDialog"
        >
          添加行
        </a-button>
        <a-button @click="handleDel">
          删除行
        </a-button>
      </template>
      <excel
        ref="exportSelect"
        file-name="接底情况"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportSelect"
        >
          导出选中
        </a-button>
      </excel>
      <excel
        ref="exportAll"
        file-name="接底情况"
        is-click-generate="false"
      >
        <a-button
          slot="excelBtn"
          @click="exportAll"
        >
          导出全部
        </a-button>
      </excel>
    </div>
    <a-table
      ref="table"
      :pagination="false"
      :columns="state !== 3?columns:columnsLook"
      :data-source="data"
      bordered
      class="bgFFF"
      :scroll="{ x: 1300 }"
      row-key="id"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
    >
      <span
        slot="index"
        slot-scope="text, record, index"
      >{{ index + 1 }}</span>
      <template
        v-for="col in ['gradeStr', 'orgName', 'employeeName','takeOverDate','remark']"
        :slot="col"
        slot-scope="text, record, index"
      >
        <div :key="col">
          <template v-if="index === editingIndex">
            <a-select
              v-if="col === 'gradeStr'"
              v-model="record.gradeId"
              @change="handleChange($event, record, col)"
            >
              <a-select-option
                v-for="item in gradeArr"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-select
              v-else-if="col === 'orgName'"
              v-model="record.orgId"
              @change="handleChange($event, record, col)"
            >
              <a-select-option
                v-for="item in orgArr"
                :key="item.id"
                :value="item.id"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
            <a-input-search
              v-else-if="col === 'employeeName'"
              v-model="record.employeeName"
              placeholder="请选择"
              @search="openPerson"
              @click="openPerson"
              @blur="handleChange($event, record.id, col)"
            />
            <a-date-picker
              v-else-if="col === 'takeOverDate'"
              v-model="record.takeOverDate"
              value-format="YYYY-MM-DD"
              type="date"
              @change="handleChange(takeOverDate, record.id, col)"
            />
            <BaseInput
              v-else
              v-model="record.remark"
              :value="text"
              @change="handleChange($event.target.value, record.id, col)"
            />
          </template>
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template
        slot="operation"
        slot-scope="text, record, index"
      >
        <div class="editable-row-operations">
          <span v-if="index === editingIndex">
            <a @click="() => save(record)">保存</a>
            <a @click="() => cancel(record)">取消</a>
          </span>
          <span v-else>
            <a
              :disabled="editingIndex !== null || state === 3"
              @click="editingIndex = index"
            >编辑</a>
          </span>
        </div>
      </template>
    </a-table>
    <pagination
      v-model="pageNo"
      :total="totalSize"
      :page-size.sync="pageSize"
      @change="handlePageChange"
      @showSizeChange="showSizeChange"
    />
    <!-- <material-list ref="detailDialog" @createList="createList"></material-list> -->
    <person-list
      ref="personList"
      @getPerson="getPerson"
    />
  </div>
</template>
<script>
import { selectOption } from '@/api/material/goods/goods'
import { situationAdd, situationDel, situationEdit, situationList } from '@/api/material/contract/clarificaiton'
import { columns,columnsLook } from './insideModel'

const data = []
export default {
	name:'a'+Date.now(),
    props: {
        state: {
            type: Number
        },
        id: {
            type: String
        }
    },
    data() {
        this.cacheData = data.map(item => ({ ...item }))
        return {
            loading: false,
            selectedRows: [],
            pageNo: 1,
            pageSize: 10,
            totalSize: 0,
            selectedRowKeys: [],
            columns: columns,
            columnsLook:columnsLook,
            editingIndex: null,
            data: [],
            gradeArr: [],
            orgArr: [],
            selectedId: [],
            gradeId: null,
            orgId: null,
            employeeName: '',
            takeOverDate: '',
            rules: {
                gradeId: { rule: 'required', message: '接底层级不能为空' },
                orgId: { rule: 'required', message: '接底部门不能为空' },
                employeeName: { rule: 'required', message: '接底人不能为空' },
                takeOverDate: { rule: 'required', message: '接底时间不能为空' }
            }
        }
    },
    watch: {},
    mounted: function() {
        this.getOrg()
        this.getGrade()
        if (this.state === 3) {
            this.editingKey = true
        }
        this.list()
        this.initErrMessage(this.rules)
        this.$refs.exportSelect.tableToExcelFile(this.$refs.table)
        this.$refs.exportAll.tableToExcelFile(this.$refs.table)
    },
    methods: {
        exportSelect: function() {
            if (this.selectedRowKeys.length > 0) {
                this.$refs.exportSelect.setDataAndGenerate(this.selectedRows)
            } else {
                this.$message.warning('请选择需要导出的数据')
            }
        },
        exportAll: function() {
            // 参数：查询条件、导出的回调
            if (this.totalSize) {
                this.pageNo = 1
                this.list(this.$refs.exportAll.setDataAndGenerate)
            } else {
                this.$message.warning('没有可导出的数据')
            }
        },
        openPerson: function() {
            this.$refs.personList.open()
        },
        getPerson: function(row) {
            this.data[this.editingIndex].employeeId = row.id
            this.data[this.editingIndex].employeeName = row.name
            this.employeeId = row.id
            this.employeeName = row.name
        },
        getGrade: function() {
            let _this = this
            selectOption({
                type: 16
            }).then(res => {
                if (res.code === 200) {
                    _this.gradeArr = res.data
                }
            })
        },
        getOrg: function() {
            let _this = this
            selectOption({
                type: 17
            }).then(res => {
                if (res.code === 200) {
                    _this.orgArr = res.data
                }
            })
        },
        openDialog: function() {
            if (this.editingIndex !== null) {
                this.$message.error('新增前请结束当前操作行')
                return
            }
            let row = {
                id: '',
                gradeId: '',
                orgId: null,
                employeeName: '',
                takeOverDate: '',
                employeeId: '',
                remark: '',
                contractConfessId: this.id
            }
            this.data.unshift(row)
            this.editingIndex = 0
        },
        // 删除
        handleDel() {
            this.delList(situationDel, () => {
                this.initTable()
                this.selectedId = []
                this.selectedRowKeys = []
                this.selectedRows = []
                this.editingIndex = null
            }, { ids: this.selectedId })
        },
        initTable() {
            this.pageNo = 1
            this.list()
        },

        async list(callback) {
            this.loading = true
            let res = await situationList({
                pageSize: callback ? this.totalSize : this.pageSize,
                pageNo: this.pageNo,
                id: this.id
            })
            if (res.code === 200) {
                if (callback) {
                    if (res.data.length) {
                        callback(res.data)
                    } else {
                        this.$message.warning('没有可导出的数据')
                    }
                    this.loading = false
                    return
                }
                this.data = res.data
                this.totalSize = res.totalSize
                this.cacheData = res.data.map(item => ({ ...item }))
            }
            this.loading = false
        },
        handleChange(val, row, col) {
            // this.$console(...arguments)
            if (col === 'gradeStr') {
                row[col] = this.gradeArr.find(v => v.id === val).name
                row['orgName'] = ''
                row['orgId'] = ''
            }
            if (col === 'orgName') {
                row[col] = this.orgArr.find(v => v.id === val).name
            }
        },
        async save(target) {
            if (!target.employeeId) {
                return this.$message.warning('接底人不能为空')
            }
            if (!target.takeOverDate) {
                return this.$message.warning('接底时间不能为空')
            }
            if (!target.gradeId) {
                return this.$message.warning('接底层级不能为空')
            }
            if (!target.orgId) {
                return this.$message.warning('接底部门不能为空')
            }
            if (target.takeOverDate) {
                target.takeOverDate = this.getNowTime(target.takeOverDate)
            }

            this.loading = true
            let res
            if (target.id) {
                res = await situationEdit(target)
            } else {
                res = await situationAdd(target)
            }
            if (res.code === 200) {
                this.$message.success('操作成功')
                this.cancel()
            }
            this.loading = false
        },
        cancel() {
            this.editingIndex = null
            this.initTable()
        },


        handlePageChange(pageNo, pageSize) {
            this.pageNo = pageNo
            this.list()
            this.selectedRowKeys = []
        },
        showSizeChange(pageNo, pageSize) {
            this.pageSize = pageSize
            this.initTable()
        },

        onSelectChange(selectedRowKeys, selectedRows) {
            this.selectedId = []
            selectedRows.map(i => {
                this.selectedId.push(i.id)
            })
            this.selectedRowKeys = selectedRowKeys
            this.selectedRows = selectedRows
        }

    }
}
</script>
